﻿using System.Reflection;

namespace PmSoft;

public interface IEntity
{
    object EntityId { get; }
}

public static partial class EntityExtensions
{
    /// <summary>
    /// 克隆实体
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    /// <param name="entity"></param>
    /// <returns></returns>
    /// <exception cref="ArgumentNullException"></exception>
    public static TEntity? Clone<TEntity>(this TEntity entity) where TEntity : class, IEntity
    {
        if (entity == null)
            return default(TEntity);

        Type entityType = typeof(TEntity);
        object? cloneEntity = Activator.CreateInstance(entityType);
        if (cloneEntity == null)
            return default(TEntity);
        PropertyInfo[] properties = entityType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
        foreach (PropertyInfo propertyInfo in properties)
        {
            if (propertyInfo.CanWrite)
                propertyInfo.SetValue(cloneEntity, propertyInfo.GetValue(entity));
        }
        return (TEntity)cloneEntity;
    }
}

